package com.dongdongshop.service.impl;

import cn.hutool.json.JSONUtil;
import com.dongdongshop.api.GoodsServiceApi;
import com.dongdongshop.common.Result;
import com.dongdongshop.constant.CacheConstant;
import com.dongdongshop.domain.vo.CartDetailVO;
import com.dongdongshop.domain.vo.CartVO;
import com.dongdongshop.dto.ItemDTO;
import com.dongdongshop.service.CartService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodsServiceApi goodsServiceApi;
    @Override
    public void addCart(Long skuId, Integer num, String autharizeToken) {
        //如果你从来没有购物车,属于第一次添加购物车数据
        //从token取出userName
        Claims claims = JwtUtil.parseJwt(autharizeToken);
        String subject = claims.getSubject();
        LoginUser loginUser = JSONUtil.toBean(subject, LoginUser.class);
        String userName = loginUser.getUname();

        //获取用户redis中的购物车,历史购物车
        List<CartVO> cartList = getCartListRedis(userName);
        //需要根据商品id去查询商品信息
        Result<ItemDTO> result = goodsServiceApi.getItemById(skuId);
        //获取商家品牌名
        if (result.getCode()!=10000){
            throw new RuntimeException("查询失败");
        }
        ItemDTO itemDTO = result.getData();
        String sellerId = itemDTO.getSeller();
        //判断当前用户有没有买过这个商家的商品
        CartVO co = getCartVOBySellerId(sellerId, cartList);
        //2没买过 ①new CartVO ②cartDetailVO ③赋值 ④存redis
        if (co == null) {
            co = new CartVO();
            co.setSellerId(itemDTO.getSeller());
            //创建购物车明细数据
            CartDetailVO detailVO = new CartDetailVO();
            detailVO.setSellerId(itemDTO.getSellerId());
            detailVO.setImage(itemDTO.getImage());
            detailVO.setNum(itemDTO.getNum());//购买的数量
            detailVO.setTotalMoney(new BigDecimal(num * itemDTO.getPrice().doubleValue()));
            detailVO.setPrice(itemDTO.getPrice());
            detailVO.setItemId(itemDTO.getId());
            detailVO.setTitle(itemDTO.getTitle());
            //创建明细集合
            List<CartDetailVO> detailVOList = new ArrayList<>();
            //将明细放入VO类
            detailVOList.add(detailVO);
            //明细放购物车里
            co.setCartDetailVOList(detailVOList);
            //放到原来的老购物车里
            cartList.add(co);
        }else {
            //3买过 co !=null
            List<CartDetailVO> cartDetailVOList = co.getCartDetailVOList();
            //从原来的
            CartDetailVO dv = getCartDetailVoByItemId(cartDetailVOList,itemDTO.getId());
            if (dv==null){//没有买过该商品
                //4买过同一商家商品,现在买别的商品 ①cartDetailVO ②赋值 ③存redis
                dv=new CartDetailVO();
                dv.setSellerId(itemDTO.getSellerId());
                dv.setImage(itemDTO.getImage());
                dv.setNum(itemDTO.getNum());//购买的数量
                dv.setTotalMoney(new BigDecimal(num * itemDTO.getPrice().doubleValue()));
                dv.setPrice(itemDTO.getPrice());
                dv.setItemId(itemDTO.getId());
                dv.setTitle(itemDTO.getTitle());
                cartDetailVOList.add(dv);
            }else {
                //5买过同一商家商品,现在还想再买之前买过的商品 ①修改数量 ②修改小记 ③存redis
                dv.setNum(dv.getNum()+num);//修改数量
                dv.setTotalMoney(new BigDecimal(dv.getNum() * dv.getPrice().doubleValue()));
                if (dv.getNum() <=0){//如果购买数量为0了,我们需要将明细对象从明细列表中移除
                    cartDetailVOList.remove(dv);
                }
                if (cartDetailVOList.isEmpty()){//如果集合中没有数据就删除集合
                    cartList.remove(co);
                }
            }
        }

        //存入redis
        addCartRedis(userName,cartList);
    }
    //从缓存中获取存入的数据
    private List<CartVO> getCartListRedis(String userName){
        List<CartVO> cartList = (List<CartVO>)redisTemplate.boundValueOps(CacheConstant.CART_CACHE_PREFIX+userName).get();
        if (cartList==null){
            cartList=new ArrayList<>();
        }
        return cartList;
    }
    //封装从集合中根据id取出
    private CartVO getCartVOBySellerId(String sellerId,List<CartVO> cartVOList){
       return cartVOList.stream().filter(vo -> Objects.equals(sellerId, vo.getSellerId())).findFirst().orElse(null);
    }
    //
    private CartDetailVO getCartDetailVoByItemId(List<CartDetailVO> cartDetailVOList,Long itemId){
       return cartDetailVOList.stream().filter(vo -> Objects.equals(itemId, vo.getItemId())).findFirst().orElse(null);
    }
    //存redis
    private void addCartRedis(String userName,List<CartVO> cartList){
        redisTemplate.boundValueOps(CacheConstant.CART_CACHE_PREFIX+userName).set(cartList);
    }

    //查询购物车
    @Override
    public List<CartVO> selectCart(String autharizeToken) {
        //从token取出userName
        Claims claims = JwtUtil.parseJwt(autharizeToken);
        String subject = claims.getSubject();
        LoginUser loginUser = JSONUtil.toBean(subject, LoginUser.class);
        String userName = loginUser.getUname();
        return getCartListRedis(userName);
    }

}
